package com.itheima;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 失败示例
 */
public class LogisticsTracking {

    // 客户授权码
    private static final String CUSTOMER = "imBQXQHb3362";
    // 密钥
    private static final String SECRET_KEY = "1762D1FBF92FEC27D3F365356E16CA5D";

    public static void main(String[] args) {
        // 模拟快递公司编码和快递单号
        String courierCode = "yuantong"; // 示例：圆通快递
        String trackingNumber = "YT7575195075749"; // 示例快递单号

        // 打印参数
        System.out.println("快递公司编码: " + courierCode);
        System.out.println("快递单号: " + trackingNumber);

        try {
            String response = queryLogistics(courierCode, trackingNumber);
            System.out.println("快递信息：" + response);
            parseResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 查询物流信息
    public static String queryLogistics(String courierCode, String trackingNumber) throws Exception {
        String apiUrl = "https://poll.kuaidi100.com/poll/query.do"; // API 地址

        // 构建请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("com", courierCode); // 快递公司编码
        paramMap.put("num", trackingNumber); // 快递单号
        paramMap.put("phone", "");         // 可选：电话号码
        paramMap.put("from", "");          // 可选：出发地
        paramMap.put("to", "");            // 可选：目的地
        paramMap.put("resultv2", "0");     // 可选：解析级别
        paramMap.put("show", "0");         // 可选：返回格式
        paramMap.put("order", "desc");     // 可选：返回结果语言

        // 生成签名
        String sign = generateSign(paramMap);

        // 使用 Apache HttpClient 发送 POST 请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(apiUrl);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // 拼接请求体
        StringBuilder requestBody = new StringBuilder();
        requestBody.append("customer=").append(CUSTOMER)
                .append("&sign=").append(sign)
                .append("&param=").append(new ObjectMapper().writeValueAsString(paramMap));

        post.setEntity(new StringEntity(requestBody.toString(), StandardCharsets.UTF_8));

        try (CloseableHttpResponse response = httpClient.execute(post)) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            return result;
        }
    }

    // 生成签名 (MD5)
    public static String generateSign(Map<String, Object> params) throws Exception {
        // 正确的签名算法：param + key + customer
        String paramStr = new ObjectMapper().writeValueAsString(params);
        String input = paramStr + SECRET_KEY + CUSTOMER;

        // 生成 MD5
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
        return byteArrayToHexString(digest).toUpperCase(); // 转为大写并返回
    }

    // 将字节数组转为十六进制字符串
    public static String byteArrayToHexString(byte[] byteArray) {
        Formatter formatter = new Formatter();
        for (byte b : byteArray) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }

    // 解析返回的 JSON 响应
    public static void parseResponse(String response) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(response);

        if (rootNode.path("result").asBoolean() == false) {
            System.out.println("查询失败: " + rootNode.path("message").asText());
            return;
        }

        // 提取并显示快递信息
        String expressNumber = rootNode.path("nu").asText();
        String status = rootNode.path("state").asText();
        System.out.println("快递单号: " + expressNumber);
        System.out.println("快递状态: " + status);

        // 打印物流轨迹
        JsonNode dataNode = rootNode.path("data");
        for (JsonNode item : dataNode) {
            String time = item.path("time").asText();
            String context = item.path("context").asText();
            System.out.println("时间: " + time + " - " + context);
        }
    }
}
